package com.shiro.controller;

import com.shiro.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@Controller
@Slf4j
public class LoginController {

    @GetMapping("/login")
    public String login(User user) {
        if (StringUtils.isEmpty(user.getUserName()) || StringUtils.isEmpty(user.getPassword())) {
            log.error("请输入用户名和密码！");
        }
        //用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                user.getUserName(),
                user.getPassword()
        );
        try {
            //进行认证，这里可以捕获异常，然后返回对应信息
            subject.login(usernamePasswordToken);
//            subject.checkRole("admin");
//            subject.checkPermissions("query", "add");
        } catch (UnknownAccountException e) {
            log.error("用户名不存在！", e);
            System.out.println("用户名不存在！");
        } catch (IncorrectCredentialsException e) {
            log.error("账号或密码错误！", e);
            System.out.println("账号或密码错误！"); ;
        } catch (AuthorizationException e) {
            log.error("没有权限！", e);
            System.out.println("没有权限");
        }
        return "index";
    }

    @RequiresRoles("admin")//注解方式鉴权，走全局异常
    @GetMapping("/create")
    @ResponseBody
    public String create() {
        return "create success!";
    }

    @RequiresPermissions("del")
    @GetMapping("/del")
    @ResponseBody
    public String del() {
        return "del success!";
    }

    @RequiresPermissions("update")
    @ResponseBody
    @GetMapping("/update")
    public String update() {
        return "update success!";
    }

    @RequiresPermissions("query")
    @GetMapping("/query")
    @ResponseBody
    public String query() {
        return "update success!";
    }

    @GetMapping({"/","/index"})
    public String index() {
        return "index";
    }

    @GetMapping({"/toLogin"})
    public String toLogin() {
        return "login";
    }

    @GetMapping({"/noauth"})
    public String noauth() {
        return "myError";
    }


}
